import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../services/mcp_service.dart';
import '../models/mcp_tool.dart';

/// MCP 连接调试页面
class McpDebugScreen extends StatefulWidget {
  const McpDebugScreen({Key? key}) : super(key: key);

  @override
  State<McpDebugScreen> createState() => _McpDebugScreenState();
}

class _McpDebugScreenState extends State<McpDebugScreen> {
  final McpService _mcpService = McpService();
  final TextEditingController _urlController = TextEditingController(
    text: 'http://localhost:8080/sse',
  );
  final List<String> _logs = [];
  final ScrollController _scrollController = ScrollController();

  bool _isConnected = false;
  bool _isConnecting = false;
  List<McpTool> _tools = [];
  String? _error;

  @override
  void initState() {
    super.initState();
    // 重定向 print 输出到日志
    _setupLogging();
  }

  @override
  void dispose() {
    _mcpService.dispose();
    _urlController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  void _setupLogging() {
    // 注意：这会影响整个应用的 print 输出
    // 在生产环境中应该使用更好的日志系统
  }

  void _addLog(String message) {
    setState(() {
      _logs.add('${DateTime.now().toString().substring(11, 19)} $message');
    });
    // 自动滚动到底部
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  Future<void> _connect() async {
    setState(() {
      _isConnecting = true;
      _error = null;
      _logs.clear();
      _tools.clear();
    });

    _addLog('🔄 开始连接到 ${_urlController.text}');

    try {
      final config = McpConfig(
        type: McpConnectionType.sse,
        sseUrl: _urlController.text,
        headers: {
          // 可以在这里添加自定义头
        },
      );

      _addLog('📝 配置创建成功');
      _addLog('   类型: SSE');
      _addLog('   URL: ${config.sseUrl}');

      await _mcpService.configure(config);

      _addLog('✅ 连接成功！');

      setState(() {
        _isConnected = true;
      });

      // 自动获取工具列表
      await _loadTools();
    } catch (e, stackTrace) {
      _addLog('❌ 连接失败: $e');
      _addLog('堆栈跟踪:');
      for (var line in stackTrace.toString().split('\n').take(5)) {
        _addLog('  $line');
      }

      setState(() {
        _error = e.toString();
        _isConnected = false;
      });
    } finally {
      setState(() {
        _isConnecting = false;
      });
    }
  }

  Future<void> _disconnect() async {
    _addLog('🔌 断开连接...');
    await _mcpService.disconnect();
    setState(() {
      _isConnected = false;
      _tools.clear();
    });
    _addLog('✅ 已断开连接');
  }

  Future<void> _loadTools() async {
    _addLog('🔧 开始获取工具列表...');

    try {
      final tools = await _mcpService.listTools();

      setState(() {
        _tools = tools;
      });

      if (tools.isEmpty) {
        _addLog('⚠️ 服务器返回了空的工具列表');
      } else {
        _addLog('✅ 成功获取 ${tools.length} 个工具:');
        for (var tool in tools) {
          _addLog('   - ${tool.name}');
          if (tool.description != null) {
            _addLog('     描述: ${tool.description}');
          }
        }
      }
    } catch (e) {
      _addLog('❌ 获取工具列表失败: $e');
      setState(() {
        _error = e.toString();
      });
    }
  }

  Future<void> _testTool(McpTool tool) async {
    _addLog('🧪 测试工具: ${tool.name}');

    try {
      // 使用空参数测试
      final result = await _mcpService.callTool(tool.name, {});

      if (result.success) {
        _addLog('✅ 工具调用成功');
        _addLog('   结果: ${result.result}');
      } else {
        _addLog('❌ 工具调用失败');
        _addLog('   错误: ${result.error}');
      }
    } catch (e) {
      _addLog('❌ 工具调用异常: $e');
    }
  }

  void _clearLogs() {
    setState(() {
      _logs.clear();
    });
  }

  void _copyLogs() {
    final logsText = _logs.join('\n');
    Clipboard.setData(ClipboardData(text: logsText));
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(const SnackBar(content: Text('日志已复制到剪贴板')));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('MCP 连接调试'),
        actions: [
          if (_isConnected)
            IconButton(
              icon: const Icon(Icons.refresh),
              onPressed: _loadTools,
              tooltip: '刷新工具列表',
            ),
          IconButton(
            icon: const Icon(Icons.copy),
            onPressed: _copyLogs,
            tooltip: '复制日志',
          ),
          IconButton(
            icon: const Icon(Icons.delete_outline),
            onPressed: _clearLogs,
            tooltip: '清空日志',
          ),
        ],
      ),
      body: Column(
        children: [
          // 连接配置区域
          _buildConnectionPanel(),

          const Divider(height: 1),

          // 主内容区域
          Expanded(
            child: Row(
              children: [
                // 左侧：日志面板
                Expanded(flex: 2, child: _buildLogPanel()),
                const VerticalDivider(width: 1),
                // 右侧：工具列表
                Expanded(flex: 1, child: _buildToolsPanel()),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildConnectionPanel() {
    return Container(
      padding: const EdgeInsets.all(16),
      color: Colors.grey[100],
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Row(
            children: [
              Expanded(
                child: TextField(
                  controller: _urlController,
                  decoration: const InputDecoration(
                    labelText: 'MCP 服务器 URL',
                    hintText: 'http://localhost:8080/sse',
                    border: OutlineInputBorder(),
                    prefixIcon: Icon(Icons.link),
                  ),
                  enabled: !_isConnecting && !_isConnected,
                ),
              ),
              const SizedBox(width: 16),
              SizedBox(
                width: 140,
                child: _isConnected
                    ? ElevatedButton.icon(
                        onPressed: _disconnect,
                        icon: const Icon(Icons.close),
                        label: const Text('断开连接'),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.red,
                          foregroundColor: Colors.white,
                        ),
                      )
                    : ElevatedButton.icon(
                        onPressed: _isConnecting ? null : _connect,
                        icon: _isConnecting
                            ? const SizedBox(
                                width: 16,
                                height: 16,
                                child: CircularProgressIndicator(
                                  strokeWidth: 2,
                                  valueColor: AlwaysStoppedAnimation<Color>(
                                    Colors.white,
                                  ),
                                ),
                              )
                            : const Icon(Icons.play_arrow),
                        label: Text(_isConnecting ? '连接中...' : '连接'),
                      ),
              ),
            ],
          ),
          if (_error != null) ...[
            const SizedBox(height: 8),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.red[50],
                border: Border.all(color: Colors.red),
                borderRadius: BorderRadius.circular(4),
              ),
              child: Row(
                children: [
                  const Icon(Icons.error_outline, color: Colors.red),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      _error!,
                      style: const TextStyle(color: Colors.red),
                    ),
                  ),
                ],
              ),
            ),
          ],
          if (_isConnected) ...[
            const SizedBox(height: 8),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.green[50],
                border: Border.all(color: Colors.green),
                borderRadius: BorderRadius.circular(4),
              ),
              child: Row(
                children: [
                  const Icon(Icons.check_circle_outline, color: Colors.green),
                  const SizedBox(width: 8),
                  const Text('已连接'),
                  const Spacer(),
                  Text('工具数量: ${_tools.length}'),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildLogPanel() {
    return Container(
      color: Colors.black,
      padding: const EdgeInsets.all(8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(8),
            child: Text(
              '调试日志 (${_logs.length})',
              style: const TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          const Divider(color: Colors.grey, height: 1),
          Expanded(
            child: _logs.isEmpty
                ? const Center(
                    child: Text(
                      '暂无日志\n点击"连接"开始调试',
                      textAlign: TextAlign.center,
                      style: TextStyle(color: Colors.grey),
                    ),
                  )
                : ListView.builder(
                    controller: _scrollController,
                    itemCount: _logs.length,
                    itemBuilder: (context, index) {
                      final log = _logs[index];
                      Color textColor = Colors.white;

                      // 根据日志内容设置颜色
                      if (log.contains('✅') || log.contains('成功')) {
                        textColor = Colors.greenAccent;
                      } else if (log.contains('❌') || log.contains('失败')) {
                        textColor = Colors.redAccent;
                      } else if (log.contains('⚠️') || log.contains('警告')) {
                        textColor = Colors.orangeAccent;
                      } else if (log.contains('📡') ||
                          log.contains('📤') ||
                          log.contains('📥')) {
                        textColor = Colors.cyanAccent;
                      } else if (log.contains('🔧') || log.contains('🧪')) {
                        textColor = Colors.yellowAccent;
                      }

                      return Padding(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 8,
                          vertical: 2,
                        ),
                        child: SelectableText(
                          log,
                          style: TextStyle(
                            color: textColor,
                            fontFamily: 'monospace',
                            fontSize: 12,
                          ),
                        ),
                      );
                    },
                  ),
          ),
        ],
      ),
    );
  }

  Widget _buildToolsPanel() {
    return Container(
      color: Colors.grey[50],
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                const Icon(Icons.build),
                const SizedBox(width: 8),
                Text(
                  '工具列表 (${_tools.length})',
                  style: const TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 16,
                  ),
                ),
              ],
            ),
          ),
          const Divider(height: 1),
          Expanded(
            child: _tools.isEmpty
                ? Center(
                    child: Text(
                      _isConnected ? '服务器没有提供工具' : '请先连接到服务器',
                      style: TextStyle(color: Colors.grey[600]),
                    ),
                  )
                : ListView.builder(
                    itemCount: _tools.length,
                    itemBuilder: (context, index) {
                      final tool = _tools[index];
                      return Card(
                        margin: const EdgeInsets.symmetric(
                          horizontal: 8,
                          vertical: 4,
                        ),
                        child: ExpansionTile(
                          leading: const Icon(Icons.extension),
                          title: Text(tool.name),
                          subtitle: Text(
                            tool.description ?? '无描述',
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                          children: [
                            Padding(
                              padding: const EdgeInsets.all(16),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  if (tool.description != null) ...[
                                    const Text(
                                      '描述:',
                                      style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                    const SizedBox(height: 4),
                                    Text(tool.description!),
                                    const SizedBox(height: 12),
                                  ],
                                  const Text(
                                    '输入参数:',
                                    style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                  const SizedBox(height: 4),
                                  Container(
                                    width: double.infinity,
                                    padding: const EdgeInsets.all(8),
                                    decoration: BoxDecoration(
                                      color: Colors.grey[200],
                                      borderRadius: BorderRadius.circular(4),
                                    ),
                                    child: SelectableText(
                                      tool.name.toString(),
                                      style: const TextStyle(
                                        fontFamily: 'monospace',
                                        fontSize: 11,
                                      ),
                                    ),
                                  ),
                                  const SizedBox(height: 12),
                                  SizedBox(
                                    width: double.infinity,
                                    child: ElevatedButton.icon(
                                      onPressed: () => _testTool(tool),
                                      icon: const Icon(Icons.play_arrow),
                                      label: const Text('测试工具 (空参数)'),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
          ),
        ],
      ),
    );
  }
}
